package com.saifan.wyy_ov.ui.property;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.MatterRequsetBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IViewOnClick;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.DateTimePickUtils;
import com.saifan.wyy_ov.utils.DialogUtil;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Date;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-5-11 16:04:50
 * @descrption 投诉建议
 */

public class ComplaintandadviceActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {
    private static final int CHOSE_CONTACTS = 1234;
    private Toolbar toolbar;
    private android.widget.ListView listView;
    private RadioButton radioButton1;
    private RadioButton radioButton2;
    private RadioGroup radiogroup;
    private EditText contacts;
    private EditText tel;
    private EditText time;
    private EditText content;
    private RoomInfoBean roomInfoBean;
    private MatterRequsetBean requsetBean;
    private String BSQD_LX = "投诉";//报事类型（工区，业主，投诉，建议）


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomInfoBean = getRoomInfoBean();
        requsetBean = new MatterRequsetBean();
        setContentView();

    }


    public void setContentView() {
        setContentView(R.layout.activity_complaintandadvice);
        this.content = (EditText) findViewById(R.id.content);
        this.tel = (EditText) findViewById(R.id.tel);
        this.contacts = (EditText) findViewById(R.id.contacts);
        this.radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
        this.radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
        this.radioButton1 = (RadioButton) findViewById(R.id.radioButton1);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        radioButton1.setOnCheckedChangeListener(this);
        radioButton2.setOnCheckedChangeListener(this);
        contacts.setText(roomInfoBean.getWYKHDA_KHMC());
        tel.setText(roomInfoBean.getWYKHDA_SJ());

    }

    public void submit(View view) {
//        if (isEmpty(contacts)) {
//            ToastUtil.showToast(this, "联系人不能为空");
//            contacts.setFocusable(true);
//            return;
//        }
//        if (isEmpty(tel)) {
//            ToastUtil.showToast(this, "联系电话不能为空");
//            tel.setFocusable(true);
//            return;
//        }
        if (isEmpty(content)) {
            content.setFocusable(true);
            ToastUtil.showToast(this, "内容不能为空");
            return;
        }

        GetData getData = new GetData();
        RequestParams params = new RequestParams();
        params.addBodyParameter(Api.Matter.MATTER, initParams());
        getData.getData(Api.Matter.MATTER_SUBMIT, params, new RequestCallBack<String>() {


            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                if (!StringUtil.isNullOrEmpty(responseInfo.result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                        String code = jsonObject.getString("Code");
                        if (code.equals("200")) {
                            ToastUtil.showToast(ComplaintandadviceActivity.this,"提交成功");
                            DialogUtil.closeProgressDialog();
                            finish();

                        } else if (code.equals("203")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(ComplaintandadviceActivity.this, getString(R.string.login_error_tip));
                        } else if (code.equals("204")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(ComplaintandadviceActivity.this, "用户名已存在 !");
                        } else if (code.equals("202")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(ComplaintandadviceActivity.this, "保存失败，信息未做修改 !");
                        } else {
                            LogUtil.e(code);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    LogUtil.e("ServerError");
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                LogUtil.i(s);
                ToastUtil.showToast(ComplaintandadviceActivity.this, getString(R.string.network_error));
                DialogUtil.closeProgressDialog();
            }


        });

    }

    public String initParams() {
        requsetBean.setBSQD_BSLR(content.getText().toString());
        requsetBean.setBSQD_CJSJ(new Date());
        requsetBean.setBSQD_LXR(contacts.getText().toString());
        requsetBean.setBSQD_LXDH(tel.getText().toString());
        requsetBean.setBSQD_LX(BSQD_LX);
        requsetBean.setBSQD_XMLX(1);
        requsetBean.setBSQD_FKGXWJ(roomInfoBean.getFKGX_ZJ());

        requsetBean.setXMBS(roomInfoBean.getXMBS());
        return new Gson().toJson(requsetBean);

    }


    public void specialServiceDate(View view) {
        DateTimePickUtils.show(this, new IViewOnClick() {
            @Override
            public void onClick(Object... object) {
                time.setText(object[0].toString());
            }
        }, new Date());
    }
 public void getContacts(View view) {
     if (Build.VERSION.SDK_INT >= 23) {
         int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
         if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
             ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS }, CHOSE_CONTACTS);
             return;
         }else {
             Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
             startActivityForResult(i, CHOSE_CONTACTS);
         }
     }else {
         Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
         startActivityForResult(i, CHOSE_CONTACTS);
     }


    }



    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            buttonView.setTextColor(Color.RED);
            if (buttonView.getId() == R.id.radioButton1) {
                BSQD_LX = "投诉";

            } else {
                BSQD_LX = "建议";
            }

        }else {
            buttonView.setTextColor(Color.BLACK);
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == CHOSE_CONTACTS) {
            if (!(resultCode == RESULT_OK)) {
                return;
            }
            if (data == null) {
                return;
            }
            Uri uri = data.getData();
            String name = "";
            String number = "";
            try {
                Cursor cursor = getContentResolver().query(uri, null, null, null,
                        null);
                if (cursor != null&&cursor.moveToFirst()) {

                    int contactId = Integer.valueOf(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
                    name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                        if (phones.moveToFirst()) {
                            //遍历所有的电话号码
                            number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        }
                    }
//
                    cursor.close();
                    tel.setText(number.replace(" ",""));
                    contacts.setText(name);
                }
            }catch (Exception e){
                LogUtil.e(e.toString());
            }




        }
    }
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
         if (requestCode == CHOSE_CONTACTS) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, CHOSE_CONTACTS);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用了读取通讯录权限", Toast.LENGTH_SHORT)
                        .show();

            }
        }



    }

}
